package com.biao.hashmap;

public class Demo05_ArrayAndLinked_HashMap<K, V> {
    private Entry[] entrys = new Entry[1000];

    class Entry<K, V> {
        K k;
        V v;
        Entry<K, V> nextEntry;  // 链表概念

        public Entry(K k, V v) {
            this.k = k;
            this.v = v;
        }
    }

    public void put(K k, V v) {
        // 加上k为空判断
        int index = k == null ? 0 : k.hashCode() % entrys.length;
        // 判断key是否产生冲突
        Entry oldEntry = entrys[index];
        if (oldEntry == null) {
            entrys[index] = new Entry<K, V>(k, v);
        } else {
            // 给下一个节点
            oldEntry.nextEntry = new Entry<K, V>(k, v);
        }
    }

    public V get(K k) {
        // 取值时判断k为空
        int index = k == null ? 0 : k.hashCode() % entrys.length;
        // 遍历链表查找数据
        for (Entry oldEntry = entrys[index]; oldEntry != null; oldEntry = oldEntry.nextEntry) {
            if ((k == null && oldEntry.k == null) || oldEntry.k.equals(k)) {
                return (V) oldEntry.v;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        Demo05_ArrayAndLinked_HashMap<Object, String> map = new Demo05_ArrayAndLinked_HashMap<>();
        map.put("a", "a");
        map.put(97, "97");
        map.put(null, "null");
        System.out.println(map.get("a"));   // a
        System.out.println(map.get(null));

    }
}
